package com.ntd.study.base.thread;

import cn.hutool.core.lang.Console;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 分支合并框架 ForkJoin
 */
public class DemoForkJoinPool {
    public static void main(String[] args) {
        final ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinSumCalculate(0l, 1000000000l);
        final Long invoke = forkJoinPool.invoke(task);
        Console.log(invoke);
    }

    static class ForkJoinSumCalculate extends RecursiveTask<Long> {

        private long start;
        private long end;

        private static final long THURSHOLD = 10000l;

        public ForkJoinSumCalculate(long start, long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            if (end - start <= THURSHOLD) {
                long sum = 0l;
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            } else {
                long middle = (start + end) / 2;
                final ForkJoinSumCalculate forkJoinSumCalculate = new ForkJoinSumCalculate(start, middle);
                forkJoinSumCalculate.fork();

                final ForkJoinSumCalculate forkJoinSumCalculate_2 = new ForkJoinSumCalculate(middle + 1, end);
                forkJoinSumCalculate_2.fork();

                return forkJoinSumCalculate.join() + forkJoinSumCalculate_2.join();
            }
        }
    }
}


